//
//  UserViewController.m
//  SmartCup
//
//  Created by Kendama on 2017/5/16.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "UserViewController.h"
#import "NSDate+FIDString.h"


@interface UserViewController ()<UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UITextFieldDelegate>
@property (strong, nonatomic) UIImageView *avatarIV;
@property (strong, nonatomic) UITextField *nicknameTF;
@property (strong, nonatomic) UILabel *sexLabel;
@property (strong, nonatomic) UILabel *heightLabel;
@property (strong, nonatomic) UILabel *weightLabel;
@property (strong, nonatomic) UILabel *ageLabel;
@property (strong, nonatomic) UIButton *loginOutButton;
@property (nonatomic, strong) UIImagePickerController * imagePicker; // 系统图片框架

@property (strong, nonatomic) NSArray *labelTitleArray;
@property (strong, nonatomic) NSMutableDictionary *userInfoDic;


@end

@implementation UserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationBar.backgroundColor = [UIColor colorWithHexString:@"3E76F6"];
}

- (void)refreshBaseControlValue {
    
    [self setLeftButtonImage:[UIImage imageNamed:@"nav_icon_back"]];
    [self setNavigationTitle:@"个人信息" titleColor:[UIColor whiteColor]];
//    [self setRightButtonTitle:@"保存"];
    self.navigationBar.backgroundColor = [UIColor colorWithHexString:@"3E76F6"];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F1F3F9"];
    
    [self getUserInfomation];
    
    [self layoutSubviews];
}

- (void)getUserInfomation
{
    GetUserInfoApi * userInfoApi = [[GetUserInfoApi alloc] init];
    [userInfoApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [userInfoApi analyseResponseObject];
        [self userInfoDic];
    } failure:^(YTKBaseRequest *request) {
        [SVProgressHUD showErrorWithStatus:@"请求超时"];
    }];
}

- (NSMutableDictionary *)userInfoDic
{
    if (!_userInfoDic) {
        _userInfoDic = [[NSMutableDictionary alloc]init];
    }
    
    NSArray *array = @[@"nickname",@"sex"
                       ,@"height",@"weight",@"birth",@"image"];
    NSDictionary *infoDic = DTCEXRACT_OBJECT(INFODIC);
    for (NSString *key in array) {
        if ([infoDic[key]length] == 0) {
            [_userInfoDic setValue:@"" forKey:key];
        }else{
            [_userInfoDic setValue:infoDic[key] forKey:key];
        }
    }
    
    return _userInfoDic;
}


#pragma mark -- 事件
//- (void)onRightButtonClick:(id)sender {
//    [self.navigationController popViewControllerAnimated:YES];
//    
//    [self updateUserInfo];
//
//}


- (void)didClickLoginOutButton {
    [[AlertViewManager shareManager]initWithMessage:@"是否退出我的账号" cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确定"] clickAtIndex:^(NSInteger buttonIndex, UIAlertView *alertView) {
        if (buttonIndex == 1) {
            DTCSAVE_OBJECT(@"NO", LOGIN);
            DTCSAVE_OBJECT(@"NO", AVATAR);
            DTCSAVE_OBJECT(@"NO", REGISTER);
            DTCSAVE_OBJECT(@"NO", SEX);

            DTCREMOVE_OBJECT(UID);
            DTCREMOVE_OBJECT(TOKEN);
            DTCREMOVE_OBJECT(IMAGE);
            [[AppDelegate defaultService]setRootViewController];
        }
    }];
}

- (void) didClickAvatarImageView {
    UIActionSheet *sheet=[[UIActionSheet alloc]initWithTitle:@"设置头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍摄照片" otherButtonTitles:@"相册", nil] ;
    [sheet showInView:self.view];
}

- (void) showSexChoose {
    [self.nicknameTF resignFirstResponder];
    [[DTPickerManager shareManager]showPickerWithSexAndPicker:^(NSArray *arr) {
        
    } andConfirm:^(NSArray *arr) {
        self.sexLabel.text = arr[0];
        if ([arr[0] isEqualToString:@"男"]) {
            [self.userInfoDic setValue:@"1" forKey:@"sex"];
        }else if ([arr[0] isEqualToString:@"女"]){
            [self.userInfoDic setValue:@"2" forKey:@"sex"];
        }
        [self updateUserInfo];

    }];
}

- (void) showHeightChoose {
    [self.nicknameTF resignFirstResponder];
    [[DTPickerManager shareManager]showPickerWithHeightAndPicker:^(NSArray *arr) {
        
    } andConfirm:^(NSArray *arr) {
        self.heightLabel.text = [NSString stringWithFormat:@"%@cm",arr[0]];
        [_userInfoDic setValue:@([arr[0]intValue]).stringValue forKey:@"height"];
        [self updateUserInfo];
    }];
}

- (void) showWeightChoose {
    [self.nicknameTF resignFirstResponder];
    [[DTPickerManager shareManager]showPickerWithWeightAndPicker:^(NSArray *arr) {
        
    } andConfirm:^(NSArray *arr) {
        self.weightLabel.text = [NSString stringWithFormat:@"%@Kg",arr[0]];
        [_userInfoDic setValue:@([arr[0]intValue]).stringValue forKey:@"weight"];
        [self updateUserInfo];
    }];
}

- (void) showAgeChoose {
    [self.nicknameTF resignFirstResponder];
    [[DTPickerManager shareManager]showPickerWithAgeAndPicker:^(NSArray *arr) {
        
    } andConfirm:^(NSArray *arr) {
        self.ageLabel.text = [NSString stringWithFormat:@"%@岁",arr[0]];
        [_userInfoDic setValue:[NSDate dateStringWithAge:arr[0]] forKey:@"birth"];
        [self updateUserInfo];

//        NSLog(@"出生年月：%@",[NSDate dateStringWithAge:arr[0]]);
    }];
}

- (void)updateUserInfo
{
    SetUserInfoApi *api = [[SetUserInfoApi alloc]initWithInfo:_userInfoDic];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dic = request.responseJSONObject;
        if ([dic[@"errcode"]intValue] == 0) {
            GetUserInfoApi * userInfoApi = [[GetUserInfoApi alloc] init];
            [userInfoApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                [userInfoApi analyseResponseObject];
                [self userInfoDic];
                if (self.updateBlock) {
                    self.updateBlock();
                }
            } failure:^(YTKBaseRequest *request) {
                [SVProgressHUD showErrorWithStatus:@"请求超时"];
            }];
        }
    } failure:^(YTKBaseRequest *request) {
        [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];

    }];
}

#pragma mark -- 代理
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (self.nicknameTF.text.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请输入昵称"];
        return;
    }
    if (self.nicknameTF.text.length > 10) {
        [SVProgressHUD showInfoWithStatus:@"昵称长度不能超过20个"];
        return;
    }
    
    if ([NSString isContainsTwoEmoji:self.nicknameTF.text] ) {
        [SVProgressHUD showInfoWithStatus:@"昵称不能使用表情"];
        return;
    }
    
    if ([self.nicknameTF.text isEqualToString:self.userInfoDic[@"nickname"]] ) {
//        [SVProgressHUD showInfoWithStatus:@"昵称未修改"];
        return;
    }
    
    NSString *string = [self.nicknameTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    [_userInfoDic setValue:string forKey:@"nickname"];
    [self updateUserInfo];
    if (self.updateBlock) {
        self.updateBlock();
    }
//    SetUserInfoApi *api = [[SetUserInfoApi alloc]initWithInfo:@{@"nickname":string}];
//    [api startWithCompletionAnimation:YES andBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
//        
////        [self.navigationController popViewControllerAnimated:YES];
//    } backfailure:^(__kindof YTKBaseRequest * _Nonnull request) {
//        
//    } requestFailure:^(__kindof YTKBaseRequest * _Nonnull request) {
//        
//    }];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    NSLog(@"buttonindex===%ld",(long)buttonIndex);
    switch (buttonIndex) {
        case 0:
            
        {
            [self formcamera];
            
        }
            break;
        case 1:
            
        {
            [self formphoto];
        }
            break;
            
        default:
            break;
    }
}

-(void)formcamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
        imagePicker.delegate = self;
        imagePicker.allowsEditing=YES;
        _imagePicker = imagePicker;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }else{
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"设备不可用" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        
    }
}
-(void)formphoto
{
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    _imagePicker = imagePicker;
    [self presentViewController:imagePicker animated:YES completion:nil];
}
#pragma mark - UIImagePickerControllerDelegate
// 完成选择
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [_imagePicker dismissViewControllerAnimated:YES completion:nil];
    UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];  // 取出被编辑的图片
    _avatarIV.image = image;
    NSData * imageData = UIImageJPEGRepresentation(image, 1.0f);
    [[NSFileManager defaultManager]removeItemAtPath:PicPath(UID) error:nil];
    
    if (imageData.length > 100 * 1024) {
        if (imageData.length > 1000 * 1024) {
            [UIImageJPEGRepresentation(image, 0.2f) writeToFile:PorPath atomically:YES];
        } else {
            [UIImageJPEGRepresentation(image, 0.4f) writeToFile:PorPath atomically:YES];
        }
    } else {
        [UIImageJPEGRepresentation(image, 1.0f) writeToFile:PorPath atomically:YES];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    
    SetUserInfoApi * setApi = [[SetUserInfoApi alloc] initWithInfo:@{@"image":PorPath}];
    [setApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        if ([[request responseJSONObject][@"errcode"] intValue] == 0) {
            GetUserInfoApi * userInfoApi = [[GetUserInfoApi alloc] init];
            [userInfoApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                [userInfoApi analyseResponseObject];
                if (self.updateBlock) {
                    self.updateBlock();
                }
            } failure:^(YTKBaseRequest *request) {
                [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
            }];
        }
    } failure:^(YTKBaseRequest *request) {
        [SVProgressHUD showInfoWithStatus:@"网络异常，请稍后再试"];
    }];
}

// 取消选择
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [_imagePicker dismissViewControllerAnimated:YES completion:nil];
}


- (void)layoutSubviews {
    
    int count = 6;
    UIView *lastView = nil;
    NSArray *array = @[self.avatarIV,self.nicknameTF,self.sexLabel,self.heightLabel,self.weightLabel,self.ageLabel];
    for(int i = 0;i < count;++i ){
        //创建一个View
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:view];
        
        UIView *line = [[UIView alloc] init];
        line.backgroundColor = [UIColor colorWithHexString:@"#D0D3DC"];

        UIImageView *arrow = [[UIImageView alloc] init];
        arrow.image = [UIImage imageNamed:@"icon_more_nor"];

        UILabel *title = [[UILabel alloc] init];
        title.font = [UIFont systemFontOfSize:15];
        title.textColor = [UIColor colorWithHexString:@"#585D6D"];
        title.text = self.labelTitleArray[i];

        
        [view addSubview:line];
        [view addSubview:arrow];
        [view addSubview:title];
        //向subView添加约束
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.equalTo(self.view);
            make.height.mas_equalTo(px1920Height(200));

            //判断是否有前一个子View
            if ( lastView ) {
                //如果有前一个View，上边界和前一个View的下边界紧贴
                make.top.mas_equalTo(lastView.mas_bottom);
            } else {
                //如果没有前一个View，上边界和container的下边界紧贴
                make.top.mas_equalTo(self.view.mas_top).with.offset(64);
            }
        }];
        
        
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(view);
            make.width.equalTo(self.view);
            make.height.mas_equalTo(1);
        }];
        
        [title mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(line).with.offset(-px1920Height(100));
            make.width.mas_equalTo(px1080Width(150));
            make.height.mas_equalTo(px1080Width(100));
            make.left.equalTo(self.view).with.offset(px1080Width(52));
        }];
        
        [arrow mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(line).with.offset(-px1920Height(100));
            make.right.equalTo(self.view).with.offset(-px1080Width(30));
            make.width.height.mas_equalTo(px1080Width(80));
        }];
        
        
        if (i == 0) {
            [view addSubview:self.avatarIV];
            [self.avatarIV mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(line).with.offset(-px1920Height(100));
                make.right.equalTo(arrow.mas_left);
                make.width.height.mas_equalTo(px1080Width(140));
            }];
        } else if (i == 1) {
            [view addSubview:self.nicknameTF];
            [self.nicknameTF mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(line).with.offset(-px1920Height(100));
                make.left.equalTo(title.mas_right);
                make.right.equalTo(arrow.mas_left);
                make.height.mas_equalTo(px1920Height(200));
            }];
        } else {
            UILabel *label = array[i];
            [view addSubview:label];
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(line).with.offset(-px1920Height(100));
                make.left.equalTo(title.mas_right);
                make.right.equalTo(arrow.mas_left);
                make.height.mas_equalTo(px1920Height(200));
            }];
        }
        //保存前一个View
        lastView = view;
    }
    
    [self.loginOutButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lastView.mas_bottom).with.offset(px1920Height(40));
        make.width.equalTo(self.view);
        make.height.mas_equalTo(px1920Height(200));
    }];
}

#pragma mark -- 懒加载
- (NSArray *)labelTitleArray
{
    if(!_labelTitleArray)
    {
//        _labelTitleArray = [[NSArray alloc]init];
        _labelTitleArray = @[@"头像",@"昵称",@"性别",@"身高",@"体重",@"年龄"];
    }
    return _labelTitleArray;
}

- (UIImageView *)avatarIV
{
    if(!_avatarIV)
    {
//        UIView *superView = self.view;
        _avatarIV = [[UIImageView alloc]init];
//        [superView addSubview:_avatarIV];
//        _avatarIV.image = [UIImage imageNamed:@"information_icon_user"];
        _avatarIV.layer.masksToBounds = YES;
        _avatarIV.layer.cornerRadius = px1080Width(140) / 2 ;
        [_avatarIV sd_setImageWithURL:[NSURL URLWithString:DTCEXRACT_OBJECT(IMAGE)] placeholderImage:[UIImage imageNamed:@"information_icon_user"]];

        _avatarIV.userInteractionEnabled = YES;
        [_avatarIV addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didClickAvatarImageView)]];
    }
    return _avatarIV;
}

- (UITextField *)nicknameTF
{
    if(!_nicknameTF)
    {
//        UIView *superView = self.view;
        _nicknameTF = [[UITextField alloc]init];
        _nicknameTF.textColor = [UIColor colorWithHexString:@"#828692"];
        _nicknameTF.font = [UIFont systemFontOfSize:15];
        _nicknameTF.textAlignment = NSTextAlignmentRight;
        _nicknameTF.text = DTCEXRACT_OBJECT(NICKNAME);
        _nicknameTF.delegate = self;
//        [superView addSubview:_nicknameTF];
    }
    return _nicknameTF;
}

- (UILabel *)sexLabel
{
    if(!_sexLabel)
    {
//        UIView *superView = self.view;
        _sexLabel = [[UILabel alloc]init];
//        [superView addSubview:_sexLabel];
        [_sexLabel setFont:[UIFont systemFontOfSize:15]];
        _sexLabel.textAlignment = NSTextAlignmentRight;
        [_sexLabel setTextColor:[UIColor colorWithHexString:@"#828692"]];
        if ([self.userInfoDic[@"sex"]isEqualToString:@"1"]) {
            _sexLabel.text = @"男";
        }else if ([self.userInfoDic[@"sex"]isEqualToString:@"2"]) {
            _sexLabel.text = @"女";
        }
        _sexLabel.userInteractionEnabled = YES;
        [_sexLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showSexChoose)]];

    }
    return _sexLabel;
}
- (UILabel *)heightLabel
{
    if(!_heightLabel)
    {
//        UIView *superView = self.view;
        _heightLabel = [[UILabel alloc]init];
//        [superView addSubview:_heightLabel];
        [_heightLabel setFont:[UIFont systemFontOfSize:15]];
        _heightLabel.textAlignment = NSTextAlignmentRight;
        [_heightLabel setTextColor:[UIColor colorWithHexString:@"#828692"]];
        _heightLabel.text = [NSString stringWithFormat:@"%@cm",self.userInfoDic[@"height"]];
        _heightLabel.userInteractionEnabled = YES;
        [_heightLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showHeightChoose)]];

    }
    return _heightLabel;
}
- (UILabel *)weightLabel
{
    if(!_weightLabel)
    {
//        UIView *superView = self.view;
        _weightLabel = [[UILabel alloc]init];
//        [superView addSubview:_weightLabel];
        [_weightLabel setFont:[UIFont systemFontOfSize:15]];
        _weightLabel.textAlignment = NSTextAlignmentRight;
        [_weightLabel setTextColor:[UIColor colorWithHexString:@"#828692"]];
        _weightLabel.text = [NSString stringWithFormat:@"%@kg",self.userInfoDic[@"weight"]];
        _weightLabel.userInteractionEnabled = YES;
        [_weightLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showWeightChoose)]];

    }
    return _weightLabel;
}
- (UILabel *)ageLabel
{
    if(!_ageLabel)
    {
        _ageLabel = [[UILabel alloc]init];
        [_ageLabel setFont:[UIFont systemFontOfSize:15]];
        _ageLabel.textAlignment = NSTextAlignmentRight;
        [_ageLabel setTextColor:[UIColor colorWithHexString:@"#828692"]];
//        NSLog(@"出生年月：%@",self.userInfoDic[@"birth"]);
        _ageLabel.text = [NSString stringWithFormat:@"%li岁",(long)[NSDate ageWithString:self.userInfoDic[@"birth"] stringDateFormatter:@"yyyy-MM-dd"]];
        _ageLabel.userInteractionEnabled = YES;
        [_ageLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showAgeChoose)]];

    }
    return _ageLabel;
}

- (UIButton *)loginOutButton
{
    if(!_loginOutButton)
    {
        UIView *superView = self.view;
        _loginOutButton = [[UIButton alloc]init];
        [superView addSubview:_loginOutButton];
        [_loginOutButton setTitle:@"退出登录" forState:UIControlStateNormal];
        [_loginOutButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        [_loginOutButton.titleLabel setFont:[UIFont systemFontOfSize:15]];
        [_loginOutButton setBackgroundColor:[UIColor whiteColor]];
        [_loginOutButton addTarget:self action:@selector(didClickLoginOutButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginOutButton;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
